package com.wyt.common.properties;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * 读取 properties 配置文件工具类
 */
public class PropertiesUtil {
    private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    private static PropertiesConfiguration config = null;

    static {
        try {
            //生产环境地址
            String rootPath = System.getProperty("user.dir");
            String path = rootPath + File.separator + "config" + File.separator + "config.properties";
            File file = new File(path);
            //开发环境地址
            if (!file.exists()) path = YamlUtils.class.getClassLoader().getResource("application.yml").getPath();
            config = new PropertiesConfiguration(path);
            config.setAutoSave(true);
            logger.info("properties文件路径path={}",path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据key获取属性文件中的值
     */
    public static String getString(String key) {
        return config.getProperty(key).toString();
    }

    /**
     * 回写属性文件中key对应的值
     */
    public static void update(String key,String value){
        try {
            config.setProperty(key, value);
        } catch (Exception e) {
            logger.error("更新属性文件异常：",e);
        }
    }

}